layui.use(['form','layer','jquery','laypage','element','laytpl'],function(){
    var $ = layui.$
        ,element = layui.element
        ,form = layui.form
        ,layPage = layui.laypage
        ,laytpl = layui.laytpl;
    //校验登录状态
    if(isNotLogIn()){
        return;
    }
    var count = 0;
    var service = "";
    //默认服务类型为2-便民服务
    var serviceType = "2";
    //模板
    var serviceOptionTpl = "{{# layui.each(d.data, function(index, item){ }}<tr itemid=\"{{item.OPTION_ID}}\"><td><input type=\"checkbox\" name=\"checked\" lay-skin=\"primary\" lay-filter=\"choose\"></td><td>{{item.OPTION_NAME}}</td><td>{{item.SERVICE_NAME}}</td><td><form class='layui-form' action=''><div class='layui-input-block'><input {{# if ( '1'==item.VALID_TAG){ }} checked= 'true'{{# } }} name='open' lay-skin='switch' lay-filter='isValid' lay-text='是|否' type='checkbox'></div></form></td><td>{{item.CREATE_USER_NAME}}</td><td>{{item.CREATE_TIME}}</td><td><button class='layui-btn layui-btn-normal layui-btn-sm edit-btn'><i class='layui-icon'>&#xe642;</i></button></td><td><button class='layui-btn layui-btn-sm layui-btn-danger delete-btn'><i class='layui-icon'>&#xe640;</i></button></td></tr>{{# }); }}";

    var index = layer.load(3);
    $.ajax({
        url : "/CivilAffairs/manager/getServiceInfo",
        type : "post",
        data:{"serviceType":serviceType},
        async : false,
        dataType : "json",
        success : function(result) {
            layer.close(index);
            if(checkResult(result)){
                $(".service-div").html(result.data);
            }
            form.render('select');
            //选择服务也重新加载表格
            form.on('select(service-filter)', function(data){
                var serviceCheck = data.value; //得到被选中的值
                if(serviceCheck!=service){
                    service = serviceCheck;
                    //重新加载一个表格
                    getServiceOptionInfo(service,serviceType);
                    removeAllSel();
                }
            });
        },
        error:function(result){
            layer.close(index);
            reqError(result,"获取服务类别异常");
        }
    });

    //获取服务信息明细
    getServiceOptionInfo(service,serviceType);

    //全选
    form.on('checkbox(selectAll)', function(data){
        var child = $(data.elem).parents('table').find('tbody input[name="checked"]:not([name="open"])');
        child.each(function(index, item){
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //获取服务明细信息
    function getServiceOptionInfo(serviceId,serviceType,page,limit){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        serviceId = isNull(serviceId)?"":serviceId;
        page = isNull(page)?0:page;
        limit = isNull(limit)?10:limit;
        var index = layer.load(3);
        //清空当前数据
        $(".service_content").html("");
        $.ajax({
            url:"/CivilAffairs/manager/getServiceOptionInfo",
            type : "post",
            data : {"serviceId":serviceId,"serviceType":serviceType,"page":page,"limit":limit},
            async : false,
            dataType : "json",
            success : function(result) {
                layer.close(index);
                if(checkResult(result)){
                    laytpl(serviceOptionTpl).render(result.data.data, function(html) {
                        $(".service_content").html(html);
                    });
                    //重新渲染
                    form.render('checkbox');
                    //需要重新加载分页
                    if(count!=result.data.count ||serviceId != service){
                        count = result.data.count;
                        service = serviceId;
                        //分页组件
                        layPage.render({
                            elem: 'news-page'
                            ,count: result.data.count //数据总数，从服务端得到
                            ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                            ,jump: function(obj, first){
                                //首次不执行
                                if(!first){
                                    console.log("not first");
                                    getServiceOptionInfo(service,serviceType,obj.curr,obj.limit);
                                }
                            }
                        });
                    }
                }
            },
            error : function(result) {
                layer.close(index);
                reqError(result,"管理员获取新闻异常");
            }
        });
    }


    //添加按钮
    $(".serviceAdd_btn").click(function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        $(window).one("resize",function(){
            var index = layui.layer.open({
                title : "新增服务",
                type : 2,
                content : "serviceAdd.html",
                success : function(layero, index){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回信息列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500)
                }
            });
            layui.layer.full(index);
        }).resize();
    });

    //编辑按钮
    $("body").on("click",".edit-btn",function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var serviceId = $(this).parents("tr").attr("itemid");
        $(window).one("resize",function(){
            //编辑文章
            var index = layui.layer.open({
                title : "编辑信息",
                type : 2,
                content : "serviceAdd.html?serviceId="+serviceId,
                success : function(layero, index){
                    setTimeout(function(){
                        layui.layer.tips('点击此处返回信息列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    },500)
                }
            });
            layui.layer.full(index);
        }).resize();
    });


    //删除
    $("body").on("click",".delete-btn",function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var _this = $(this);
        layer.confirm('确定删除此信息？',{icon:3, title:'提示信息'},function(index){
            //_this.parents("tr").remove();
            var optionId = _this.parents("tr").attr("itemid");
            deleteServiceOption(optionId);
            layer.close(index);
        });
    });

    //信息内容有效与否的切换
    form.on('switch(isValid)', function(data){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var isValid = this.checked ?"1":"0";
        var optionId = $(this).parents("tr").attr("itemid");
        var index = layer.load(3);
        $.ajax({
            url:"/CivilAffairs/manager/changeValidTag",
            type:"post",
            data:{"isValid":isValid,"dataId":optionId,"dataType":"serviceOption"},
            dataType:"json",
            success:function(result){
                layer.close(index);
                if(checkResult(result)){
                    layer.msg(result.detail,{icon:6});
                }
            },
            error : function(result) {
                layer.close(index);
                console.log((this.checked?"展示":"不展示")+"新闻:"+result.status+","+result.statusMessage+",newsId:"+newsId);
                layer.msg("切换信息展示标识异常,请稍后重试",{icon:2});
            }
        });

    });

    //删除信息
    function deleteServiceOption(optionId,isAllDel){
        if(isNotLogIn()||isNull(optionId)){
            return;
        }
        $.ajax({
            url : "/CivilAffairs/manager/deleteServiceOption",
            type : "post",
            data : {"optionId":optionId},
            async : false,
            dataType : "json",
            success : function(result) {
                if(checkResult(result) && !isAllDel){
                    getServiceOptionInfo(service,serviceType,0,10);
                }
            },
            error:function(result){
                reqError(result,"删除信息异常");
            }
        });
    }

    //批量删除
    $(".batchDel").click(function(){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        var $checkbox = $('.service_content tr input[name="checked"]');
        var $checked = $('.service_content tr input[name="checked"]:checked');
        if($checkbox.is(":checked")){
            layer.confirm('确定删除选中的信息？',{icon:3, title:'提示信息'},function(index){
                var index = layer.msg('删除中，请稍候',{icon: 16,time:false,shade:0.8});
                //删除数据
                $checked.each(function(){
                    var optionId = $(this).parents("tr").attr("itemid");
                    deleteServiceOption(optionId,true);
                });
                getServiceOptionInfo(service,serviceType,0,10);
                layer.close(index);
                layer.msg("删除成功",{icon:6});
            });
        }else{
            layer.msg("请选择需要删除的信息");
        }
    });

    var searchCount = 0;
    var optionName = "";
    //搜索
    $(".search_btn").click(function () {
        var searchName = $(".search_input").val();
        if(isNull(searchName)){
            layer.msg("请输入要搜索的服务名称");
            return;
        }
        searchNameInfo(searchName);
    });

    //判断回车
    $(document).keyup(function (e) {//捕获文档对象的按键弹起事件
        if (e.keyCode == 13) {
            $(".search_btn").click();
        }
    });

    function searchNameInfo(searchName,page,limit){
        //校验登录状态
        if(isNotLogIn()){
            return;
        }
        page = isNull(page)?0:page;
        limit = isNull(limit)?10:limit;
        var index = layer.load(3);
        $.ajax({
            url : "/CivilAffairs/manager/getServiceOptionInfo",
            type : "post",
            data : {"serviceId":service,"searchName":searchName,"page":page,"limit":limit},
            async : false,
            dataType : "json",
            success : function(result) {
                layer.close(index);
                if("0000"==result.status){
                    laytpl(serviceOptionTpl).render(result.data.data, function(html) {
                        $(".service_content").html(html);
                    });
                    //重新渲染
                    form.render('checkbox');
                    //需要重新加载分页
                    if(searchCount!=result.data.count || name != searchName){
                        searchCount = result.data.count;
                        optionName = searchName;
                        //分页组件
                        layPage.render({
                            elem: 'news-page'
                            ,count: result.data.count //数据总数，从服务端得到
                            ,layout: ['count', 'prev', 'page', 'next', 'limit', 'skip']
                            ,jump: function(obj, first){
                                //首次不执行
                                if(!first){
                                    searchNameInfo(searchName,obj.curr,obj.limit);
                                }
                            }
                        });
                    }
                }else{
                    var serviceName = getServiceNameById(service);
                    var detail = isNull(service)&&isNull(serviceName)?"":"在服务分类:[ "+serviceName+" ]中";
                    layer.msg(detail+"未查询到服务[ "+searchName+" ]的信息",{icon:2});
                }

            },
            error:function(result){
                layer.close(index);
                reqError(result,"搜索服务信息异常");
            }
        });
    }

    //根据服务id获取服务名称
    function getServiceNameById(serviceId){
        var serviceName = "";
        $("#services option").each(function () {
            if($(this).val()==serviceId){
                serviceName = $(this).text();
            }
        });
        return serviceName;
    }

    //通过判断文章是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)",function(data){
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="open"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="open"]):checked')
        if(childChecked.length == child.length){
            $(data.elem).parents('table').find('thead input#selectAll').get(0).checked = true;
        }else{
            $(data.elem).parents('table').find('thead input#selectAll').get(0).checked = false;
        }
        form.render('checkbox');
    });




});